﻿Imports System.Collections.ObjectModel
Imports System.IO.Ports
Imports System.Net
Imports System.Net.Sockets
Imports GalaSoft.MvvmLight
Imports GalaSoft.MvvmLight.CommandWpf
Imports FL_8x0.Common.SystemData
Imports FL_8x0.Common
Imports GalaSoft.MvvmLight.Messaging

Namespace FL_8x0.Viewmodel

    Public Class ConnectInfoViewModel : Inherits ViewModelBase

        Private _model As String
        Private _version As String

        Private _mode As String                        '连接模式
        Private _other As String
        Private _modbus As String                      '协议
        Private _id As String                          '设备Modbus Id

        Private _localIp As String                     '本地IP（上位机）
        Private _localPort As String                   '本地Port（上位机）

        Private _remoteIp As String                    '设备IP
        Private _remotePort As String                  '设备Port

        Private _portName As String                     '串口号
        Private _baudRate As String                     '波特率
        Private _dataBits As String                     '数据位
        Private _stopBits As String                     '停止位
        Private _parity As String                       '校验位

        Private _modelList As ObservableCollection(Of String)
        Private _versionList As ObservableCollection(Of String)
        Private _otherList As ObservableCollection(Of String)
        Private _modeList As ObservableCollection(Of String)
        Private _protocolList As ObservableCollection(Of String)
        Private _portNameList As ObservableCollection(Of String)
        Private _baudRateList As ObservableCollection(Of String)
        Private _stopBitslList As ObservableCollection(Of String)
        Private _dataBitsList As ObservableCollection(Of String)
        Private _parityList As ObservableCollection(Of String)

        Private _modeEnable As Boolean
        Private _modbusEnable As Boolean
        Private _otherEnable As Boolean
        Private _versionEnable As Boolean
        Private _netEnable As Boolean                   ' 网口可用
        Private _uartEnable As Boolean                  ' 串口可用
        Private _localIpEnable As String                ' 本地IP可用
        Private _localPortEnable As String              ' 本地Port可用
        Private _remoteIpEnable As String               ' 设备IP可用
        Private _remotePortEnable As String             ' 设备Port可用


        Private _applyCommand As RelayCommand(Of Window)   '点击“确认”触发命令
        Private _cancelCommand As RelayCommand(Of Window)  '点击“取消”触发命令

        Public Sub New()

            ModelList = New ObservableCollection(Of String)(SystemData.ModelList)

            VersionList = SystemData.Versions_800

            ModeList = New ObservableCollection(Of String) From {
                "uart", "tcp-server", "tcp-client", "udp"
                }

            ProtocolList = New ObservableCollection(Of String) From {
                "ASCII", "RTU", "TCP"
                }

            PortNameList = New ObservableCollection(Of String)(New List(Of String)(SerialPort.GetPortNames()))

            BaudRateList = New ObservableCollection(Of String) From {
                "1200", "2400", "9600", "14400", "19200", "38400", "56000", "57600", "115200"}
            DataBitsList = New ObservableCollection(Of String) From {
                "7", "8"
                }
            StopBitslList = New ObservableCollection(Of String) From {
                "1", "1.5", "2"
                }
            ParityList = New ObservableCollection(Of String) From {
                "O", "E", "N"
                }

            Dim strLocalName As String = Dns.GetHostName  '获得本地计算机的主机名
            Dim localIps() As IPAddress = Dns.GetHostEntry(strLocalName).AddressList '获得本地计算机的IP地址
            Dim defaultIp = "192.168.0.7"
            For Each ip In localIps
                If ip.AddressFamily = AddressFamily.InterNetwork Then
                    defaultIp = ip.ToString()
                End If
            Next
            LocalIp = defaultIp
            Dim strJsonData As String
            Dim jsonResult As Newtonsoft.Json.Linq.JObject
            Try

                strJsonData = My.Computer.FileSystem.ReadAllText(g_strStartupPath & "\JSON\Machine.json", Text.Encoding.UTF8)
                jsonResult = Newtonsoft.Json.Linq.JObject.Parse(strJsonData)
                Model = jsonResult.Item("machine") '协议

                If Model = "FL_830" Then
                    strJsonData = My.Computer.FileSystem.ReadAllText(g_strStartupPath & "\JSON\modbus.json", Text.Encoding.UTF8)
                    jsonResult = Newtonsoft.Json.Linq.JObject.Parse(strJsonData)
                    Protocol = jsonResult.Item("protocol") '协议
                    Id = jsonResult.Item("modbus id")
                    Mode = jsonResult.Item("type")
                    PortName = jsonResult.Item("uart port")
                    BaudRate = jsonResult.Item("uart baud(bps)") 'COM号
                    DataBits = jsonResult.Item("uart data")  'COM号
                    Parity = jsonResult.Item("uart Parity")
                    StopBits = jsonResult.Item("uart stop")
                    LocalPort = jsonResult.Item("local port") '本地端口号
                    RemoteIp = jsonResult.Item("remote ip")     '远程IP
                    RemotePort = jsonResult.Item("remote port")  '远程端口
                Else
                    Protocol = jsonResult.Item("modbus") '协议
                    Id = jsonResult.Item("id")
                    Version = jsonResult.Item("version")
                    Other = jsonResult.Item("other")
                    Mode = jsonResult.Item("commMode")
                    PortName = jsonResult.Item("portName")
                    BaudRate = jsonResult.Item("baudRate") 'COM号
                    DataBits = jsonResult.Item("dataBits")  'COM号
                    Parity = jsonResult.Item("parity")
                    StopBits = jsonResult.Item("stopBits")
                    LocalPort = jsonResult.Item("localPort") '本地端口号
                    RemoteIp = jsonResult.Item("remoteIP")     '远程IP
                    RemotePort = jsonResult.Item("remotePort")  '远程端口
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

            ApplyCommand = New RelayCommand(Of Window)(Sub(window) Apply(window))
            CancelCommand = New RelayCommand(Of Window)(Sub(window) Cancel(window))
        End Sub

        '=====================================================================
        '函 数 名: Apply
        '参    数: window 窗口
        '返 回 值:
        '功能描述: 数据写入json、注册表存储
        '=====================================================================
        Private Sub Apply(ByVal window As Window)
            Dim strJsonData As String
            Dim jsonResult As Newtonsoft.Json.Linq.JObject


            If SystemData.Machine <> Model Then
                Messenger.Default.Send(Of String)(Model, "Machine-Select")
                Database.ReopenDataBase(SystemData.g_strDatabaseProvider, SystemData.g_strDatabasePath & "\" & Model & "\",
                                        SystemData.SUPER_USER_NAME, SystemData.SUPER_PASSWORD)
            End If

            SystemData.Machine = Model
            SystemData.Version = Version

            strJsonData = My.Computer.FileSystem.ReadAllText(g_strStartupPath & "\JSON\Machine.json", Text.Encoding.UTF8)
            jsonResult = Newtonsoft.Json.Linq.JObject.Parse(strJsonData)

            jsonResult.Item("machine") = Model
            jsonResult.Item("version") = Version
            jsonResult.Item("other") = Other
            jsonResult.Item("commMode") = Mode


            If ModbusEnable Then
                Try
                    My.Computer.FileSystem.WriteAllText(g_strStartupPath & "\JSON\Machine.json", jsonResult.ToString, False)
                    strJsonData = My.Computer.FileSystem.ReadAllText(g_strStartupPath & "\JSON\modbus.json", Text.Encoding.UTF8)
                    jsonResult = Newtonsoft.Json.Linq.JObject.Parse(strJsonData)
                    If Mode = "uart" Then
                        jsonResult.Item("uart port") = PortName  'COM号
                        jsonResult.Item("uart baud(bps)") = BaudRate  'COM号
                        jsonResult.Item("uart data") = DataBits 'COM号
                        jsonResult.Item("uart Parity") = Parity
                        jsonResult.Item("uart stop") = StopBits
                        jsonResult.Item("protocol") = Protocol
                        jsonResult.Item("modbus id") = Id
                        '连接方式
                        '协议
                        '端口号
                    ElseIf Mode = "tcp-server" Then
                        jsonResult.Item("local port") = LocalPort  '本地端口号
                        jsonResult.Item("protocol") = Protocol  'Modbus协议
                        jsonResult.Item("modbus id") = Id
                    ElseIf Mode = "tcp-client" Then
                        jsonResult.Item("remote ip") = RemoteIp  '远程IP
                        jsonResult.Item("remote port") = RemotePort '远程端口
                        jsonResult.Item("protocol") = Protocol 'Modbus协议
                        jsonResult.Item("modbus id") = Id
                    ElseIf Mode = "udp" Then
                        jsonResult.Item("remote ip") = RemoteIp  '远程IP
                        jsonResult.Item("remote port") = RemotePort  '远程IP
                        jsonResult.Item("local ip") = LocalIp  '本地端口号
                        jsonResult.Item("local port") = LocalPort  '本地端口号
                        jsonResult.Item("protocol") = Protocol 'Modbus协议
                        jsonResult.Item("modbus id") = Id
                    End If
                    jsonResult.Item("type") = Mode
                    My.Computer.FileSystem.WriteAllText(g_strStartupPath & "\JSON\modbus.json", jsonResult.ToString, False)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
                SystemData.strLink = ""
            Else

                jsonResult.Item("portName") = PortName
                jsonResult.Item("baudRate") = BaudRate
                jsonResult.Item("dataBits") = DataBits
                jsonResult.Item("parity") = Parity
                jsonResult.Item("stopBits") = StopBits


                My.Computer.FileSystem.WriteAllText(g_strStartupPath & "\JSON\Machine.json", jsonResult.ToString, False)

                If SystemData.strLink = "" Then
                    SystemData.strLink = PortName & "," & BaudRate & "," & SystemData.Machine & "," & SystemData.Version & "," & Other
                    Messenger.Default.Send(Of String)(Other, "Mode-Select")
                Else
                    Dim links = SystemData.strLink.Split(",")
                    If links(4) <> Other Then
                        SystemData.strLink = PortName & "," & BaudRate & "," & SystemData.Machine & "," & SystemData.Version & "," & Other
                        Messenger.Default.Send(Of String)(Other, "Mode-Select")
                    End If
                End If
                SystemData.strLink = PortName & "," & BaudRate & "," & SystemData.Machine & "," & SystemData.Version & "," & Other
            End If


            window.DialogResult = True
        End Sub

        '=====================================================================
        '函 数 名: Cancel
        '参    数: window 窗口
        '返 回 值:
        '功能描述: 取消关闭
        '=====================================================================
        Private Sub Cancel(ByVal window As Window)
            window.DialogResult = True
        End Sub


        Public Property Mode As String
            Get
                Return _mode
            End Get
            Set(value As String)
                _mode = value
                If value = "uart" Then
                    NetEnable = False
                    RemoteIpEnable = False
                    RemotePortEnable = False
                    LocalIpEnable = False
                    LocalPortEnable = False
                    UartEnable = True
                ElseIf value = "tcp-server" Then
                    UartEnable = False
                    NetEnable = True
                    RemoteIpEnable = False
                    RemotePortEnable = False
                    LocalPortEnable = True
                    LocalIpEnable = True
                ElseIf value = "tcp-client" Then
                    UartEnable = False
                    NetEnable = True
                    RemoteIpEnable = True
                    RemotePortEnable = True
                    LocalPortEnable = False
                    LocalIpEnable = False
                ElseIf value = "udp" Then
                    UartEnable = False
                    NetEnable = True
                    RemoteIpEnable = True
                    RemotePortEnable = True
                    LocalPortEnable = True
                    LocalIpEnable = True
                End If
                RaisePropertyChanged()
            End Set
        End Property

        Public Property Protocol As String
            Get
                Return _modbus
            End Get
            Set(value As String)
                _modbus = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property Id As String
            Get
                Return _id
            End Get
            Set(value As String)
                _id = value
            End Set
        End Property

        Public Property LocalIp As String
            Get
                Return _localIp
            End Get
            Set(value As String)
                _localIp = value
            End Set
        End Property

        Public Property LocalPort As String
            Get
                Return _localPort
            End Get
            Set(value As String)
                _localPort = value
            End Set
        End Property

        Public Property RemoteIp As String
            Get
                Return _remoteIp
            End Get
            Set(value As String)
                _remoteIp = value
            End Set
        End Property

        Public Property RemotePort As String
            Get
                Return _remotePort
            End Get
            Set(value As String)
                _remotePort = value
            End Set
        End Property

        Public Property PortName As String
            Get
                Return _portName
            End Get
            Set(value As String)
                _portName = value
            End Set
        End Property

        Public Property BaudRate As String
            Get
                Return _baudRate
            End Get
            Set(value As String)
                _baudRate = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property DataBits As String
            Get
                Return _dataBits
            End Get
            Set(value As String)
                _dataBits = value
            End Set
        End Property

        Public Property StopBits As String
            Get
                Return _stopBits
            End Get
            Set(value As String)
                _stopBits = value
            End Set
        End Property

        Public Property Parity As String
            Get
                Return _parity
            End Get
            Set(value As String)
                _parity = value
            End Set
        End Property

        Public Property ModeList As ObservableCollection(Of String)
            Get
                Return _modeList
            End Get
            Set(value As ObservableCollection(Of String))
                _modeList = value
            End Set
        End Property

        Public Property ProtocolList As ObservableCollection(Of String)
            Get
                Return _protocolList
            End Get
            Set(value As ObservableCollection(Of String))
                _protocolList = value
            End Set
        End Property

        Public Property PortNameList As ObservableCollection(Of String)
            Get
                Return _portNameList
            End Get
            Set(value As ObservableCollection(Of String))
                _portNameList = value
            End Set
        End Property

        Public Property BaudRateList As ObservableCollection(Of String)
            Get
                Return _baudRateList
            End Get
            Set(value As ObservableCollection(Of String))
                _baudRateList = value
            End Set
        End Property

        Public Property StopBitslList As ObservableCollection(Of String)
            Get
                Return _stopBitslList
            End Get
            Set(value As ObservableCollection(Of String))
                _stopBitslList = value
            End Set
        End Property

        Public Property DataBitsList As ObservableCollection(Of String)
            Get
                Return _dataBitsList
            End Get
            Set(value As ObservableCollection(Of String))
                _dataBitsList = value
            End Set
        End Property

        Public Property ParityList As ObservableCollection(Of String)
            Get
                Return _parityList
            End Get
            Set(value As ObservableCollection(Of String))
                _parityList = value
            End Set
        End Property

        Public Property NetEnable As Boolean
            Get
                Return _netEnable
            End Get
            Set(value As Boolean)
                _netEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property UartEnable As Boolean
            Get
                Return _uartEnable
            End Get
            Set(value As Boolean)
                _uartEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property LocalIpEnable As String
            Get
                Return _localIpEnable
            End Get
            Set(value As String)
                _localIpEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property LocalPortEnable As String
            Get
                Return _localPortEnable
            End Get
            Set(value As String)
                _localPortEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property RemoteIpEnable As String
            Get
                Return _remoteIpEnable
            End Get
            Set(value As String)
                _remoteIpEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property RemotePortEnable As String
            Get
                Return _remotePortEnable
            End Get
            Set(value As String)
                _remotePortEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property ApplyCommand As RelayCommand(Of Window)
            Get
                Return _applyCommand
            End Get
            Set(value As RelayCommand(Of Window))
                _applyCommand = value
            End Set
        End Property

        Public Property CancelCommand As RelayCommand(Of Window)
            Get
                Return _cancelCommand
            End Get
            Set(value As RelayCommand(Of Window))
                _cancelCommand = value
            End Set
        End Property

        Public Property Model As String
            Get
                Return _model
            End Get
            Set(value As String)
                If _model <> value Then
                    Version = ""
                    Other = ""
                    If value.Contains("800") Then
                        Protocol = ""
                        OtherEnable = True
                        ModbusEnable = False
                        ModeEnable = False
                        Mode = "uart"
                        Select Case value
                            Case SystemData.Model_800
                                VersionEnable = True
                                Version = VersionList(0)
                                OtherList = SystemData.Modes_800
                                Other = OtherList(0)
                            Case SystemData.Model_800MS
                                VersionEnable = False
                                OtherList = SystemData.Modes_800MS
                                Version = ""
                                Other = OtherList(0)
                        End Select
                    Else
                        OtherEnable = False
                        ModbusEnable = True
                        VersionEnable = False
                        ModeEnable = True
                    End If
                    _model = value
                    RaisePropertyChanged()
                End If
            End Set
        End Property

        Public Property Version As String
            Get
                Return _version
            End Get
            Set(value As String)
                _version = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property Other As String
            Get
                Return _other
            End Get
            Set(value As String)
                _other = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property ModelList As ObservableCollection(Of String)
            Get
                Return _modelList
            End Get
            Set(value As ObservableCollection(Of String))
                _modelList = value
            End Set
        End Property

        Public Property OtherList As ObservableCollection(Of String)
            Get
                Return _otherList
            End Get
            Set(value As ObservableCollection(Of String))
                _otherList = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property VersionList As ObservableCollection(Of String)
            Get
                Return _versionList
            End Get
            Set(value As ObservableCollection(Of String))
                _versionList = value
            End Set
        End Property

        Public Property ModbusEnable As Boolean
            Get
                Return _modbusEnable
            End Get
            Set(value As Boolean)
                _modbusEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property OtherEnable As Boolean
            Get
                Return _otherEnable
            End Get
            Set(value As Boolean)
                _otherEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property VersionEnable As Boolean
            Get
                Return _versionEnable
            End Get
            Set(value As Boolean)
                _versionEnable = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property ModeEnable As Boolean
            Get
                Return _modeEnable
            End Get
            Set(value As Boolean)
                _modeEnable = value
                RaisePropertyChanged()
            End Set
        End Property
    End Class
End Namespace